package pers.mine.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.mine.po.Member;
import pers.mine.po.Order;
import pers.mine.service.inter.MemberService;
import pers.mine.service.inter.OrderService;
import pers.mine.vo.Info;

/**
 * @author Mine
 * @since 2016年10月22日_下午11:20:51
 */
@Controller
@RequestMapping()
@Scope("session") 
public class MemberController {
	private Info logininfo = new Info();// 放到登录页的信息
	private Info indexinfo = new Info();// 放到首页的信息
	private String regPageFlag = "active"; // 页面clas样式字符,控制显示登录/注册
	@Autowired
	MemberService memberService;
	@Autowired
	OrderService orderService;

	/**
	 * 获得登录页面
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String adminLogin(Model model, HttpServletRequest request) {
		System.out.println(request.getAttribute("logininfo"));
		System.out.println(request.getSession().getAttribute("logininfo"));
		if (request.getAttribute("logininfo") == null
				&& request.getSession().getAttribute("logininfo") == null) {
			logininfo.setType(Info.INFO);
			logininfo.setMsg("欢迎来到会员[登录页面]");
			model.addAttribute("logininfo", logininfo);
		}
		return "memberLoginOrReg";
	}

	/**
	 * 获得注册选项卡页面
	 */
	@RequestMapping(value = "/reg", method = RequestMethod.GET)
	public String adminReg(HttpServletRequest request) {
		if (request.getAttribute("logininfo") == null
				|| request.getSession().getAttribute("logininfo") == null) {
			logininfo.setType(Info.INFO);
			logininfo.setMsg("欢迎来到会员[注册页面]");
			request.setAttribute("logininfo", logininfo);
		}
		// 切换到注册选项卡
		request.setAttribute("regPageFlag", regPageFlag);
		return "memberLoginOrReg";
	}

	/**
	 * 获得用户信息/订单记录查看页面
	 */
	@RequestMapping(value = "/member/{id}", method = RequestMethod.GET)
	public String getInfo(@PathVariable("id") Integer mid, Model model,
			HttpSession session) {
		Member x = (Member) session.getAttribute("member");
		if (mid.intValue() != x.getId().intValue()) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("用户未登录...");
			model.addAttribute("indexinfo", indexinfo);
			return "forward:indexshow";
		}
		List<Order> iOrderInfo = orderService.findPageByMid(mid);
		indexinfo.setType(Info.INFO);
		indexinfo.setMsg("欢迎来到会员[信息查看]页面");
		model.addAttribute("indexinfo", indexinfo);
		model.addAttribute("iOrderInfo", iOrderInfo);
		return "member/iMember";
	}

	/**
	 * 获得修改用户信息页面
	 */
	@RequestMapping(value = "/member/edit/{id}", method = RequestMethod.GET)
	public String editInfo(@PathVariable("id") Integer mid, Model model,
			HttpSession session) {
		Member x = (Member) session.getAttribute("member");
		if (mid.intValue() != x.getId().intValue()) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("用户未登录...");
			model.addAttribute("indexinfo", indexinfo);
			return "forward:indexshow";
		}
		indexinfo.setType(Info.INFO);
		indexinfo.setMsg("欢迎来到会员[信息修改]页面");
		model.addAttribute("indexinfo", indexinfo);
		return "member/editInfo";
	}

	/**
	 * 修改用户信息
	 */
	@RequestMapping(value = "/member/edit/{id}", method = RequestMethod.POST)
	public String doedit(@PathVariable("id") Integer mid, Member member,
			Model model, HttpSession session) {
		Member x = (Member) session.getAttribute("member");
		if (mid.intValue() != x.getId().intValue()) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("用户未登录...");
			model.addAttribute("indexinfo", indexinfo);
			return "forward:/indexshow";
		}
		member.setPw(null);
		member.setState(null);
		member.setBalance(null);
		if (memberService.editMemberInfo(member)) {
			indexinfo.setType(Info.SUCCESS);
			indexinfo.setMsg("会员基本信息修改成功!");
			indexinfo.setCanChange(false);
			model.addAttribute("indexinfo", indexinfo);
			indexinfo = new Info();
			// 更新session
			Member newMember = memberService.getOneMemberByID(mid);
			if (newMember != null) {
				session.setAttribute("member", newMember);
			}
			return "forward:/indexshow";
		} else {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("会员基本信息修改失败0.0");
			model.addAttribute("indexinfo", indexinfo);
			return "member/editInfo";
		}
	}

	/**
	 * 修改用户密码
	 */
	@RequestMapping(value = "/member/editpw/{id}", method = RequestMethod.POST)
	public String doeditpw(@PathVariable("id") Integer mid, String oldpw,
			String newpw, String renewpw, Model model, HttpSession session) {
		Member x = (Member) session.getAttribute("member");
		if (mid.intValue() != x.getId().intValue()) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("用户未登录...");
			model.addAttribute("indexinfo", indexinfo);
			return "forward:/indexshow";
		}
		// 校验参数表单参数
		if (valiNull(oldpw) && valiNull(newpw) && valiNull(renewpw)) {
			if (newpw.equals(renewpw)) {// 两次新密码一致性检验
				Member dbMember = memberService.getOneMemberByID(mid);
				if (dbMember != null && dbMember.getState().intValue() == 1
						&& oldpw.equals(dbMember.getPw())) {// 验证旧密码
															// 可以修改
					Member one = new Member();
					one.setId(mid);
					one.setPw(newpw);
					// 执行修改
					if (memberService.editMemberInfo(one)) {
						indexinfo.setMsg("[密码修改操作]:修改成功^_^");
						indexinfo.setCanChange(false);
						model.addAttribute("indexinfo", indexinfo);
						indexinfo = new Info();
						// 更新session
						Member newMember = memberService.getOneMemberByID(mid);
						if (newMember != null) {
							session.setAttribute("member", newMember);
						}
						return "forward:/indexshow";
					} else {
						indexinfo.setMsg("[密码修改操作]:修改失败,未知原因0.0");
					}
				} else {
					indexinfo.setMsg("[密码修改操作]:会员旧密码输入错误0.0");
				}
			} else {
				indexinfo.setMsg("[密码修改操作]:两次新密码输入不一致0.0");
			}
		} else {
			indexinfo.setMsg("[密码修改操作]:存在为空的参数。。。0.0");
		}
		indexinfo.setType(Info.ERROR);
		model.addAttribute("indexinfo", indexinfo);
		return "member/editInfo";
	}

	/**
	 * 执行注册操作[加入注解校验]
	 * 
	 * @return
	 */
	@RequestMapping(value = "/reg", method = RequestMethod.POST)
	public String Reg(@Valid Member member, BindingResult result, String repw,
			Model model, HttpSession session) {
		if (result.hasErrors()) {
			StringBuilder errMsg = new StringBuilder();
			logininfo.setType(Info.ERROR);

			errMsg.append("[注册错误信息]:");
			List<ObjectError> errorList = result.getAllErrors();
			for (ObjectError error : errorList) {
				errMsg.append(error.getDefaultMessage() + ";");
				// System.out.println(error.getDefaultMessage());
			}
			logininfo.setMsg(errMsg.toString());
			model.addAttribute("pageFlag", regPageFlag);
			model.addAttribute("logininfo", logininfo);
			return "memberLoginOrReg";
		}
		System.out.println(member);
		System.out.println(repw);
		if (member == null) {
			logininfo.setType(Info.ERROR);
			logininfo.setMsg("[注册信息]:请先填写数据...");
			model.addAttribute("logininfo", logininfo);
			model.addAttribute("pageFlag", regPageFlag);
			return "memberLoginOrReg";
		}
		if (repw == null || !repw.equals(member.getPw())) {
			logininfo.setType(Info.ERROR);
			logininfo.setMsg("[注册信息]:两次密码不一致...");
			model.addAttribute("logininfo", logininfo);
			model.addAttribute("pageFlag", regPageFlag);
			return "memberLoginOrReg";
		}
		if (memberService.register(member)) {
			logininfo.setType(Info.SUCCESS);
			logininfo.setMsg("[注册信息]:#" + member.getId() + "注册成功,可以进行登录^_^");
		} else {
			logininfo.setType(Info.ERROR);
			logininfo.setMsg("[注册信息]:注册失败,未知原因...");
			// 切换到注册选项卡
			model.addAttribute("pageFlag", regPageFlag);
		}
		model.addAttribute("logininfo", logininfo);
		return "memberLoginOrReg";

	}

	/**
	 * 执行登录操作
	 * 
	 * @param id
	 * @param name
	 * @return
	 */

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String Login(Integer id, String pw, Model model, HttpSession session)
			throws Exception {

		if (id == null || id < 1 || pw == null || "".equals(pw.trim())) {
			logininfo.setType(Info.ERROR);
			logininfo.setMsg("[登录信息]:用户名或密码为空...");
			// model.addAttribute("logininfo", logininfo);
			return "memberLoginOrReg";
		}
		Member one = memberService.login(id, pw);
		System.out.println(one);
		if (one != null) {
			// 放入session
			session.setAttribute("member", one);

			return "redirect:indexshow";
		} else {
			logininfo.setType(Info.ERROR);
			logininfo.setMsg("[登录信息]:登录失败！{账号不存在或账户不可用或用户名、密码输入有误...}");
			model.addAttribute("logininfo", logininfo);
			return "memberLoginOrReg";
		}
	}

	/**
	 * 执行充值操作
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/recharge")
	public String recharge(Integer id, Double money, Model model,
			HttpSession session) {
		indexinfo.setCanChange(false);
		if (this.valiNumber(id, money)) {
			// 对比session信息
			Member sessionOne = this.getSessionMember(session);
			if (sessionOne != null && id == sessionOne.getId().intValue()) {
				// 查询数据库最新余额信息
				Member dbOne = memberService.getOneMemberByID(id);
				if (dbOne != null) {
					// 金额计算
					Double newBalance = money + dbOne.getBalance();
					// 执行更新操作
					if (memberService.setMemberBalance(id, newBalance)) {
						indexinfo.setType(Info.SUCCESS);
						indexinfo.setMsg("[充值信息]:#" + id + "号用户余额已更新为"
								+ newBalance + "(￥)...");
						dbOne.setBalance(newBalance);
						session.setAttribute("member", dbOne);// 放入新用户信息
						model.addAttribute("indexinfo", indexinfo);
						return "forward:indexshow";// 充值成功就去首页吧
					} else {
						indexinfo.setMsg("[充值信息]:充值失败,未知原因...");
					}
				} else {
					indexinfo.setMsg("[充值信息]:非法操作,#" + id + "号用户不存在...");
				}
			} else {
				indexinfo.setMsg("[充值信息]:非法操作,#" + id + "号用户未登录...");
			}
		} else {
			indexinfo.setMsg("[充值信息]:非法数据请求...");
		}
		indexinfo.setType(Info.ERROR);
		model.addAttribute("indexinfo", indexinfo);
		return "forward:indexshow";// 充值失败也去首页吧
	}

	/**
	 * 执行注册账户验证操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/valiReg", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	Info valiReg(String id) {
		Info valiInfo = new Info();// 验证信息
		if (!valiNull(id) || id.length() < 4) {
			valiInfo.setType(Info.SPAN_WARNING);
			valiInfo.setMsg("注册账号不能为空,或长度小于4");
			return valiInfo;
		}
		id = id.trim();// 去空格
		Integer one = null;
		try {
			one = new Integer(id);
			if (one < 1) {
				valiInfo.setType(Info.SPAN_WARNING);
				valiInfo.setMsg("注册账号不能小于1...");
				return valiInfo;
			}
			if (memberService.validate(one)) {
				valiInfo.setType(Info.SPAN_SUCCESS);
				valiInfo.setMsg("可以注册...");
			} else {
				valiInfo.setType(Info.SPAN_IMPORTANT);
				valiInfo.setMsg("账号已存在...");
			}
		} catch (Exception e) {
			valiInfo.setType(Info.SPAN_DEFAULT);
			valiInfo.setMsg("注册账号必须是纯数字,或数字过大...");
		}
		return valiInfo;
	}

	/**
	 * 获得logout页面
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String getAdminLogout(HttpSession session) {
		return "memberLogout";
	}

	private boolean valiNull(String str) {
		if (str == null || "".equals(str.trim())) {
			return false;
		}
		return true;
	}

	private boolean valiNumber(Object... objects) {
		for (Object obj : objects) {
			if (obj == null) {
				return false;
			}
			if (obj instanceof Double) {
				if (((Double) obj).doubleValue() <= 0) {
					return false;
				}
			}
			if (obj instanceof Integer) {
				if (((Integer) obj).intValue() <= 0) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 获取session用户，加入强转检测
	 * 
	 * @param session
	 * @return
	 */
	private Member getSessionMember(HttpSession session) {
		Object obj = session.getAttribute("member");
		if (obj != null && obj instanceof Member) {
			return (Member) obj;
		}
		return null;
	}
}
